package com.pms.partitionPoints.web;

import com.pms.exception.R;
import com.pms.partitionPoints.bean.EquipmentBean;
import com.pms.partitionPoints.bean.EquipmentDataBean;
import com.pms.partitionPoints.entity.KyEquipmentUploadData;
import com.pms.partitionPoints.entity.KyOrganization;
import com.pms.partitionPoints.entity.KyOrganizationEquipment;
import com.pms.partitionPoints.service.IKyGroupOrganizationService;
import com.pms.partitionPoints.service.IKyOrganizationEquipmentService;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.repair.entity.KyCardRecharge;
import com.pms.util.DateUtil;
import com.pms.util.idutil.SnowFlake;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.partitionPoints.service.IKyEquipmentInfoService;
import com.pms.partitionPoints.entity.KyEquipmentInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("kyEquipmentInfo")
@Api(value="测点管理",description = "测点管理")
public class KyEquipmentInfoController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IKyEquipmentInfoService kyEquipmentInfoService;
    @Autowired
    IKyOrganizationEquipmentService kyOrganizationEquipmentService;
    @Autowired
    IKyGroupOrganizationService kyGroupOrganizationService;
    @Autowired
    IKyOrganizationService kyOrganizationService;
    /**
         * 新增
         * @param entity
         * @return
         */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "测点新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name="name",value="测点名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="equipmenttypeid",value="设备类型Id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="dataacquisitionmode",value="数据采集方式",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="equipmentidentification",value="设备标识",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="longitude",value="纬度",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="latitude",value="经度",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="phoneno",value="负责人电话",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="managername",value="负责人名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="equipmentaddress",value="设备地址",required = false,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="dmaid",value="所属分区id字符串拼接",required = false,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="description",value="备注",required = false,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="organizationgroupid",value="顶级分区id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="cardphone",value="测点卡电话号码",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="pollinterval",value="轮询间隔:秒数",required = true,dataType = "String",paramType="application/json")
    })
    public R add(@RequestBody KyEquipmentInfo entity){
//        Assert.isBlank(orgIds,"分区所属机构不能为空");
        String code = request.getHeader("X-Code");
        Assert.isBlank(code,"系统编码不能为空");
        Assert.isBlank(entity.getName(),"测点名称不能为空");
        Assert.isNull(entity.getEquipmenttypeid(),"设备类型Id不能为空");
        Assert.isNull(entity.getDataacquisitionmode(),"数据采集方式不能为空");
        Assert.isBlank(entity.getEquipmentidentification(),"设备标识不能为空");
        Assert.isBlank(entity.getLatitude(),"经度不能为空");
        Assert.isBlank(entity.getLongitude(),"纬度不能为空");
        Assert.isBlank(entity.getPhoneno(),"负责人电话不能为空");
        Assert.isNull(entity.getManagername(),"负责人名称不能为空");
        Assert.isNull(entity.getOrganizationgroupid(),"顶级分区id不能为空");
        Assert.isBlank(entity.getDmaid(),"测点绑定分区不能为空");
        Assert.isBlank(entity.getCardphone(),"测点卡电话号码不能为空");
        EntityWrapper<KyEquipmentInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("cardPhone",entity.getCardphone());
        int k = kyEquipmentInfoService.selectCount(wrapper);
        if(k>0){
            return  R.error("测点卡号码已存在");
        }
        if(entity.getStatus()==null){
            entity.setStatus(1);
        }
        entity.setCreatetime(new Date());
        entity.setInstallationtime(new Date());
        entity.setDirection(5);
        String orgIds = entity.getDmaid();
        String name = entity.getName();
        String equipmentidentification = entity.getEquipmentidentification();
        EntityWrapper<KyEquipmentInfo> ew = new EntityWrapper<>();
        ew.eq("name",name);
        ew.eq("organizationGroupId",entity.getOrganizationgroupid());
        int i = kyEquipmentInfoService.selectCount(ew);
        if(i>0){
            return  R.error("测点名称已存在");
        }
        EntityWrapper<KyEquipmentInfo> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("equipmentIdentification",equipmentidentification);
        int j = kyEquipmentInfoService.selectCount(entityWrapper);
        if(j>0){
            return  R.error("设备标识已存在");
        }
        KyCardRecharge cardRecharge=new KyCardRecharge();
        Long cardId=new SnowFlake(0,0).nextId();
        cardRecharge.setCardId(cardId);
        cardRecharge.setTotalAmount(new BigDecimal(0));//总金额
        cardRecharge.setCurrentBalance(new BigDecimal(0));//当前余额
        cardRecharge.setRecentlyCurrentBalance(new BigDecimal(0));//最近充值金额
        cardRecharge.setRecentlyData(null);//最近充值时间
        cardRecharge.setRecentlyName(null);//最近充值人
        cardRecharge.setEquipmentInfoName(entity.getName());//设备名称
        cardRecharge.setPhone(entity.getCardphone());//测点卡电话号码
        cardRecharge.setState(1);
        cardRecharge.setMonthlyFeeStandard(new BigDecimal(0));//每月消费标准
        cardRecharge.setCrtTime(new Date());
        cardRecharge.setCrtUser(getCurrentUserMap().get("userName"));
        try{
            kyEquipmentInfoService.insertEquipmentInfoAndOrgs(entity,orgIds,cardRecharge);
        }catch (Exception e){
            return R.error("测点新增异常");
        }
        return R.ok();
    }
    /**
     * 修改
     * @param entity
     * @return
     */
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "测点修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="测点id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="name",value="测点名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="equipmenttypeid",value="设备类型Id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="dataacquisitionmode",value="数据采集方式",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="equipmentidentification",value="设备标识",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="longitude",value="纬度",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="latitude",value="经度",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="phoneno",value="负责人电话",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="managername",value="负责人名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="equipmentaddress",value="设备地址",required = false,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="dmaid",value="所属分区id字符串拼接",required = false,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="description",value="备注",required = false,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="organizationgroupid",value="顶级分区id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="cardphone",value="测点卡电话号码",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="pollinterval",value="轮询间隔:秒数",required = true,dataType = "String",paramType="application/json")
    })
    public R update(@RequestBody KyEquipmentInfo entity){
        Assert.isBlank(entity.getName(),"测点名称不能为空");
        Assert.isNull(entity.getEquipmenttypeid(),"设备类型Id不能为空");
        Assert.isNull(entity.getDataacquisitionmode(),"数据采集方式不能为空");
        Assert.isBlank(entity.getEquipmentidentification(),"设备标识不能为空");
        Assert.isBlank(entity.getLatitude(),"经度不能为空");
        Assert.isBlank(entity.getLongitude(),"纬度不能为空");
        Assert.isBlank(entity.getPhoneno(),"电话不能为空");
        Assert.isNull(entity.getManagername(),"负责人名称不能为空");
        Assert.isNull(entity.getOrganizationgroupid(),"顶级分区id不能为空");
        Assert.isBlank(entity.getPhoneno(),"测点卡电话号码不能为空");
        EntityWrapper<KyEquipmentInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("cardPhone",entity.getCardphone());
        KyEquipmentInfo kei = kyEquipmentInfoService.selectOne(wrapper);
        if(kei!=null){
            if(kei.getId().intValue()!=entity.getId().intValue()){
                return  R.error("测点卡号码已存在");
            }
        }
        String name = entity.getName();
        String equipmentidentification = entity.getEquipmentidentification();
        EntityWrapper<KyEquipmentInfo> ew = new EntityWrapper<>();
        ew.eq("name",name);
        ew.eq("organizationGroupId",entity.getOrganizationgroupid());
        KyEquipmentInfo info = kyEquipmentInfoService.selectOne(ew);
        if(info!=null){
            if(info.getId().intValue()!=entity.getId().intValue()){
                return  R.error("测点名称已存在");
            }
        }
        EntityWrapper<KyEquipmentInfo> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("equipmentIdentification",equipmentidentification);
        KyEquipmentInfo keiInfo = kyEquipmentInfoService.selectOne(entityWrapper);
        if(keiInfo!=null){
            if(keiInfo.getId().intValue()!=entity.getId().intValue()){
                return  R.error("设备标识已存在");
            }
        }
        try{
            kyEquipmentInfoService.updateEquipmentInfo(entity);
        }catch (Exception e){
            return  R.error("测点编辑异常");
        }
        return R.ok();
    }

    /**
     * findByID
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测点详情")
    @ApiImplicitParam(name="id",value="测点id",required = true,dataType = "Integer",paramType="form")
    public R findById(@PathVariable int id){
        KyEquipmentInfo kyEquipmentInfo = kyEquipmentInfoService.selectById(id);
        return R.ok().put("data",kyEquipmentInfo);
    }

    /**
     * 测点禁用(启用)
     * @param id
     * @return
     */
    @RequestMapping(value = "/forbiddenById",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "测点禁用(启用)")
    @ApiImplicitParam(name="id",value="测点id",required = true,dataType = "Integer",paramType="form")
    public R forbiddenById(int id){
        KyEquipmentInfo kyEquipmentInfo = kyEquipmentInfoService.selectById(id);
        if(kyEquipmentInfo.getStatus()==1){
            kyEquipmentInfo.setStatus(2);
        }else if(kyEquipmentInfo.getStatus()==2){
            kyEquipmentInfo.setStatus(1);
        }
        try {
            kyEquipmentInfoService.updateEquipmentInfo(kyEquipmentInfo);
        }catch (Exception e){
            return  R.error("测点状态修改异常");
        }
        return R.ok();
    }

    /**
 * 删除
 * @param id
 * @return
 */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    @ApiOperation(value = "测点删除")
    @ApiImplicitParam(name="id",value="测点id",required = true,dataType = "Integer",paramType="form")
    public R deleteById(@PathVariable int id){
        KyEquipmentInfo kyEquipmentInfo = kyEquipmentInfoService.selectById(id);
        kyEquipmentInfo.setStatus(3);
        try{
            kyEquipmentInfoService.updateEquipmentInfo(kyEquipmentInfo);
        }catch (Exception e){
            return  R.error("测点删除异常");
        }
        return R.ok();
    }

    /**
     * 测点管理列表
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测点管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="offset",value="分页条数",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="strName",value="搜索字段",required = false,dataType = "String",paramType="form")
    })
    public R page(@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1")int offset,Integer orgId,String strName){
        KyOrganization kyOrganization = kyOrganizationService.selectById(orgId);
        Assert.isNull(kyOrganization,"没有对应的分区");
        String orgIds = "";
        if(kyOrganization.getOrganizationgradeid()==1){
            String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
            Assert.isBlank(type,"用户类型不能为空");
            String companyCode = request.getHeader("X-Code");
            Assert.isBlank(companyCode,"系统编码不能为空");
            String roleId = request.getHeader("X-groupId");
            Assert.isBlank(roleId,"角色id不能为空");
            Assert.isNull(orgId,"机构id不能为空");
            if(type.equals("2")){
                String ids = kyGroupOrganizationService.getOrgIdsStrByGroupId(roleId);
                String str = orgId.toString();
                String [] arr = ids.split(",");
                StringJoiner joiner = new StringJoiner(",");
                if(arr.length>0){
                    for(int i=0;i<arr.length;i++){
                        if(!str.equals(arr[i])){
                            joiner.add(arr[i]);
                        }

                    }
                }
                orgIds = joiner.toString();
            }else{
                orgIds = orgId.toString();
            }
        }else{
            orgIds = orgId.toString();
        }
        Page<Map<String,Object>> page = new Page<Map<String,Object>>(offset,limit);
        EntityWrapper ew = new EntityWrapper<KyEquipmentInfo>();
        kyEquipmentInfoService.queryEquipmentListByOrgId(page,ew,orgIds,strName);
        return R.ok().put("data",page);
    }

    /**
     * 测点报表详情-历史数据
     * findByOrgId
     * @param id
     * @return
     */
    @RequestMapping(value = "/findByOrgId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测点报表详情-历史数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="测点id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="limit",value="分页条数,默认10",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="offset",value="分页页码，默认为1",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="orgMaxId",value="分区id",required = true,dataType = "Integer",paramType="form")
    })
    public R findByOrgId(int id,@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1")int offset,Integer orgMaxId){
        Assert.isNull(id,"测点id不能为空");
        Assert.isNull(orgMaxId,"测点所在机构的顶级机构id不能为空");
        Page<KyEquipmentUploadData> page = new Page<KyEquipmentUploadData>(offset,limit);
        EntityWrapper ew = new EntityWrapper<KyOrganizationEquipment>();
        ew.eq("keud.equipmentId",id);
        ew.orderBy("keud.acquisitionTime",false);
        Page<KyEquipmentUploadData> equipmentDataPage = kyOrganizationEquipmentService.queryEquipmentDateListById(page,ew,orgMaxId);
        return R.ok().put("data",equipmentDataPage);
    }

    /**
     * 测点曲线分析
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getEquipmentCurveAnalysis",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测点曲线分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgMaxId",value="顶级分区id",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="equIds",value="测点拼接字符串",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="开始时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="结束时间",required = true,dataType = "String",paramType="form")
    })
    public R getEquipmentCurveAnalysis(Integer orgMaxId,String equIds,String startTime,String endTime){
        Assert.isNull(orgMaxId,"顶级机构id");
        Assert.isBlank(equIds,"测点拼接字符串");
        Assert.isNull(startTime,"开始时间不能为空");
        Assert.isNull(endTime,"结束时间不能为空");
        Date startDate = DateUtil.stringToDate(startTime);
        Date endDate = DateUtil.stringToDate(endTime);
        Set<Map<String,Object>> set = new HashSet<>();
        String[] idArr = equIds.split(",");
        List<String> idList = Arrays.asList(idArr);
        List<EquipmentBean> list = kyOrganizationEquipmentService.getEquipmentDateByIdAndTime(orgMaxId,idList,startDate,endDate);
//        for(int i=0;i<idArr.length;i++){
//            Map<String,Object> map = new HashMap<>();
//            Integer id = Integer.parseInt(idArr[i]);
//            KyEquipmentInfo ko = kyEquipmentInfoService.selectById(id);
//            List<KyEquipmentUploadData> list = kyOrganizationEquipmentService.getEquipmentDateByIdsAndTime(orgMaxId,id,startDate,endDate);
//            map.put("name",ko.getName());
//            map.put("id",id);
//            map.put("list",list);
//            set.add(map);
//        }

        return R.ok().put("data",list);
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<KyEquipmentInfo> all(){
        return kyEquipmentInfoService.selectList(null);
    }

    @RequestMapping(value = "/getStatementEquipmentInfoPage", method = RequestMethod.GET)
    @ApiOperation(value = "测点报表分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name="offset",value="当前页码，默认为1",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="limit",value="分页数量，默认为10",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="equIds",value="测点id,字符串拼接",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="开始时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="结束时间",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="orgMaxId",value="当前顶级机构id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="name",value="测点名称",required = false,dataType = "String",paramType="form")
    })
    public R getStatementEquipmentInfoPage(@RequestParam(defaultValue = "1")Integer offset,@RequestParam(defaultValue = "10")Integer limit,String equIds,String startTime,String endTime,Integer orgMaxId,String name) {
        Assert.isNull(equIds,"测点id不能为空");
        Assert.isNull(startTime,"开始时间不能为空");
        Assert.isNull(endTime,"结束时间不能为空");
        Assert.isNull(orgMaxId,"最顶级分区id不能为空");
        Date startDate = DateUtil.stringToDate(startTime);
        Date endDate = DateUtil.stringToDate(endTime);
        EntityWrapper ew = new EntityWrapper<KyOrganizationEquipment>();
        String[] strArray = equIds.split(",");
        List<Integer> list = new ArrayList<>();
        for(String str:strArray){
            int a = Integer.valueOf(str);
            list.add(a);
        }
        Page<EquipmentDataBean> page = new Page<EquipmentDataBean>(offset,limit);
        Page<EquipmentDataBean> equipmentPage = kyOrganizationEquipmentService.queryEquipmentPages(page,ew,orgMaxId,list,startDate,endDate,name);
        return R.ok().put("data",equipmentPage);
    }

//    public R test(){
//        List<String> al = Arrays.asList("a","b","c","d");
//        al.forEach(x->{
//            System.out.println("print value : "+x);
//
//        });
//        al.forEach(KyEquipmentInfoController::forbiddenById);
//
//        return  R.ok();
//    }
}